package a51qindian.com.comprehensive.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.activity.ChooseStaffActivity;
import a51qindian.com.comprehensive.adapter.RepairAdapter;
import a51qindian.com.comprehensive.base.QDBaseFragment;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.RepairInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import butterknife.BindView;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/22 0022
 * Description: 维修单
 */

public class RepairFragment extends QDBaseFragment {


    @BindView(R.id.recycler_repair)
    RecyclerView mRecyclerRepair;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;

    private String mType = "";
    private static final int REQUEST_CODE=0x123;
    private int mPos;
    private RepairAdapter mAdapter;
    private List<RepairInfo> mRepairInfoList;

    public static RepairFragment newInstance(String type) {

        Bundle args = new Bundle();
        args.putString(REPAIR_TYPE, type);
        RepairFragment fragment = new RepairFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mRepairInfoList = new ArrayList<>();
        mType = getArguments().getString(REPAIR_TYPE, "");
        mRecyclerRepair.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerRepair.addItemDecoration(new LinearItemDecoration());
        mAdapter = new RepairAdapter(mContext, mType);
        mRecyclerRepair.setAdapter(mAdapter);
        mAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                mPos=pos;
                RepairInfo repairInfo = mRepairInfoList.get(pos);
                Intent intent = new Intent(mContext, ChooseStaffActivity.class);
                intent.putExtra("rp_id", repairInfo.getRp_id());
                intent.putExtra("source", "repair");
                startActivityForResult(intent,REQUEST_CODE);
            }
        });
        setSmartRefreshLayout(mLayoutRefresh);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showRepairList(mUid, mType, String.valueOf(mPage + 1));
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showRepairList(mUid, mType, "0");
    }

    public static final String REPAIR_TYPE = "type";
    public static final String REPAIR_UN_FINISHED = "0";
    public static final String REPAIR_FINISHED = "1";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_repair;
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        if (mType.equals(REPAIR_UN_FINISHED)) {
            showRepairList(mUid, mType, "0");
        }
    }

    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
        if (mType.equals(REPAIR_FINISHED)) {
            showRepairList(mUid, mType, "0");
        }
    }


    /**
     * 显示维修列表
     *
     * @param uid  用户编号
     * @param type 类型 0：未分配，1：已分配
     */
    private void showRepairList(String uid, String type, String page) {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("status", type);
        map.put("page", page);
        mLayoutContent.onLoadingWithContent();
        ObservableHelper.createObservable(RetrofitCreator.createService().repairList(map))
                .subscribe(new SelectorObserver<BaseModel<List<RepairInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<RepairInfo>> listBaseModel) {
                        List<RepairInfo> repairInfoList = listBaseModel.getData();

                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage=0;
                            mRepairInfoList.clear();
                        }else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh&&repairInfoList.size()< Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mRepairInfoList.addAll(repairInfoList);
                        mAdapter.setRepairInfoList(mRepairInfoList);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopRefreshLoad();
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(mContext, e.getMessage());
                    }
                });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CODE&&resultCode== Activity.RESULT_OK) {
            mRepairInfoList.remove(mPos);
            mAdapter.notifyItemRemoved(mPos);
        }
    }
}
